package test;

public class BitConvert {
	public static String Hex2Str(byte[] b) {
		StringBuffer d = new StringBuffer(b.length * 2);
		for (int i = 0; i < b.length; i++) {
			char hi = Character.forDigit((b[i] >> 4) & 0x0F, 16);
			char lo = Character.forDigit(b[i] & 0x0F, 16);
			d.append(Character.toUpperCase(hi));
			d.append(Character.toUpperCase(lo));
		}
		return d.toString();
	}
	
	public static byte[] Str2Hex(String str) {
		char[] ch = str.toCharArray();
		byte[] b = new byte[ch.length / 2];
		for (int i = 0; i < ch.length; i++) {
			if (ch[i] == 0) {
				break;
			}
			if (ch[i] >= '0' && ch[i] <= '9') {
				ch[i] = (char) (ch[i] - '0');
			} else if (ch[i] >= 'A' && ch[i] <= 'F') {
				ch[i] = (char) (ch[i] - 'A' + 10);
			}
		}
		for (int i = 0; i < b.length; i++) {
			b[i] = (byte) (((ch[2 * i] << 4) & 0xf0) + (ch[2 * i + 1] & 0x0f));
		}
		return b;
	}

	public static String Str2HexDecimal(String src) throws NullPointerException {
		if (src == null) {
			throw new NullPointerException();
		}
		byte[] bytesarr = src.getBytes();
		byte[] des = new byte[8];
		System.arraycopy(bytesarr, 0, des, 0, 8);
		return Hex2Str(des);
	}
	
	public static int byteArrayToInt(byte[] b) {
	    int value = 0;
	    for (int i = b.length; i > 0; i--) {
	        int shift = ( b.length - i ) * 8;
	        value += (b[i - 1] & 0x000000FF) << shift;
	    }
	    return value;
	}
}
